# coding: utf-8

from django.http import HttpResponseRedirect, HttpResponse
from djangoext.mako import render_to_response , render_to_string, render_string

import time, datetime
import re
import cStringIO
import os
import random
import types, operator
from shangjie.utils import log, cache
from shangjie.utils import lunar

from shangjie.conf import settings
from sqlalchemy.sql import *

from functools import partial

from oa.utils import *


def expresslist( req ):
    # 资讯列表
    flag, reqobj = get_reqobj( req )
    if not flag: return HttpResponse( {  'rspcode': 8004, 'rspinfo': reqobj } )
    search = reqobj.get('search','').decode('utf-8').encode('gbk')
    msg = reqobj.get('strExpressType','').decode('utf-8').encode('gbk')
    
    pageSize = reqobj.get('pageSize','50').decode('utf-8').encode('gbk')
    pageNum = reqobj.get('pageNum','1').decode('utf-8').encode('gbk')
    sort_by = '_id'
    sort_order = 'desc'
    sub_sql = ""
    start_num = (int(pageNum)-1)*int(pageSize)
    
    se = settings.DB_SESSION()
    content = {}
    sql = "select * from zhsq_express where status !='3' "
    if search:
        sql = sql + " and expresstype like '%%%s%%'"%(search)
    log.info("select",sql)
    rs = se.execute( sql.decode('gbk') ).fetchall()
    
    record_count = taotal = len(rs)
    page_count = record_count / int(pageSize) if record_count % int(pageSize) == 0 else record_count / int(pageSize) + 1
    if sort_by: sub_sql += """ order by %s %s""" % (sort_by, sort_order)
    sub_sql = """ limit %s, %s""" % (start_num, pageSize)
    sql += sub_sql
    log.info("proVerigy",sql)
    rs = se.execute( sql.decode('gbk') ).fetchall()
    content['pageSize'] = pageSize
    content['pageNum'] = pageNum
    content['record_count'] = record_count
    content['page_count'] = page_count
    
    content['rs'] = rs
    content['search'] = search
    content['strExpressType'] = msg
    content['XQ_DICT'] = XQ_DICT
    return render_to_response( 'CMS/express/expresslist.html',content )    

def expresslist_old(req):
    flag, reqobj = get_reqobj(req)
    if not flag: return HttpResponse({'rspcode': 8004, 'rspinfo': reqobj})
    communityId = reqobj.get('communityId', '').decode('utf-8')
    search = reqobj.get('search', '').decode('utf-8')
    se = settings.DB_SESSION()
    content = {}
    sql = "select * from zhsq_express where status !='3'"
    if search:
        sql = sql + " and expresstype like '%%%s%%' "%search
    log.info('express', sql)
    rs = se.execute(sql).fetchall()
    content["rs"] = rs
    return render_to_response('CMS/express/expresslist.html',content)

def addexpress_old(req):
    return render_to_response('CMS/express/addexpress.html')
def addexpress(req):
    flag, reqobj = get_reqobj( req )
    if not flag: return HttpResponse( {  'rspcode': 8004, 'rspinfo': reqobj } )
    communityId = reqobj.get('communityId','').decode('utf-8').encode('gbk')
    search = reqobj.get('search','').decode('utf-8').encode('gbk')
    msg = reqobj.get('strExpressType','').decode('utf-8').encode('gbk')
    pcid = reqobj.get('pcid','').decode('utf-8').encode('gbk')
    se = settings.DB_SESSION()
    sql =   "select a.pid as pid ,a.pName as pName, a.pMobile as pMobile,b.hid as hid ,c.houseNum as houseNum ,c.belongBuildingNum as belongBuildingNum,c.belongBuildingUnit as belongBuildingUnit from zhsq_owner a, zhsq_house2owner b, zhsq_house c where b.hid=c.hid and a.pid = b.pid "
    if search :
        sql = sql + " and (a.pName like '%%%s%%' or a.pMobile like '%%%s%%')"%(search,search)
    log.info("owner",sql)
    rs = se.execute( sql.decode('gbk') ).fetchall()
    content = {}
    content['communityId'] = communityId
    content['search'] = search
    content['msg'] = msg
    content['result_list'] = rs
    content['pcid'] = pcid
    content['XQ_DICT'] = XQ_DICT
    content['GS_DICT'] = GS_DICT
    return render_to_response('CMS/express/addexpress.html', content)

def addexpressall( req ):
    flag, reqobj = get_reqobj( req )
    if not flag: return HttpResponse( {  'rspcode': 8004, 'rspinfo': reqobj } )
    communityId = reqobj.get('communityId','').decode('utf-8').encode('gbk')
    search = reqobj.get('search','').decode('utf-8').encode('gbk')
    msg = reqobj.get('strExpressType','').decode('utf-8').encode('gbk')
    pcid = reqobj.get('pcid','').decode('utf-8').encode('gbk')
    se = settings.DB_SESSION()
    sql =   "select * from zhsq_employee where  1=1 and eState !='2'"
    if search :
        sql = sql + " and (eName like '%%%s%%' or mobile like '%%%s%%')"%(search,search)
    log.info("employee",sql)
    rs = se.execute( sql.decode('gbk') ).fetchall()
    content = {}
    content['communityId'] = communityId
    content['search'] = search
    content['msg'] = msg
    content['rs'] = rs
    content['pcid'] = pcid
    content['XQ_DICT'] = XQ_DICT
    content['GS_DICT'] = GS_DICT
    return render_to_response( 'CMS/express/addexpressall.html' , content )    

def saveexpressall( req ):
    flag, reqobj = get_reqobj( req )
    if not flag: return HttpResponse( {  'rspcode': 8004, 'rspinfo': reqobj } )
    search = reqobj.get('search','').decode('utf-8').encode('gbk')
    msg = reqobj.get('strExpressType','').decode('utf-8').encode('gbk')
    eid = reqobj.get('eid','').decode('utf-8').encode('gbk')
    se = settings.DB_SESSION()
    sql =   "select * from zhsq_employee where 1 = 1" 
    sql = sql + " and eid = '%s' " %(eid)
    log.info("owner",sql)
    row = se.execute( sql.decode('gbk') ).fetchone()
    eName =  row.eName.encode('gbk')
    # print type(eName),type(row.eName),row.eName
    mobile = row.mobile.encode('gbk')
    sql_insert = """insert into zhsq_express(trackid, expresstype, fromuser, touser, address,phone, createtime, status,userid,detailaddress) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s','%s')""" % (
        "", msg, "", eName, u"物业办公室".encode('gbk'), mobile,
        datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), '1', eid,"")
    # print type(sql_insert),sql_insert
    se.execute(sql_insert.decode('gbk'))
    mailsql = "insert into zhsq_jpush ( status, titleid,title, userid, createtime, content, pushtype,usertype) values (  '1', '2', '快递', '%s', '%s', '您有新快递' , '0','0')" % (mobile,datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    se.execute(mailsql.decode('utf-8'))
    
    return HttpResponseRedirect( '/CMS/express/addexpressall.ht?search=%s&strExpressType=%s'%(search.decode('gbk').encode('utf-8'),msg.decode('gbk').encode('utf-8')))

def saveexpress( req ):
    flag, reqobj = get_reqobj( req )
    if not flag: return HttpResponse( {  'rspcode': 8004, 'rspinfo': reqobj } )
    search = reqobj.get('search','').decode('utf-8').encode('gbk')
    msg = reqobj.get('msg','').decode('utf-8').encode('gbk')
    eid = reqobj.get('eid','').decode('utf-8').encode('gbk')
    ad = reqobj.get('ad','').decode('utf-8').encode('gbk')
    se = settings.DB_SESSION()
    sql =   "select * from zhsq_owner where 1 = 1" 
    sql = sql + " and pid = '%s' " %(eid)
    log.info("owner",sql)
    row = se.execute( sql.decode('gbk') ).fetchone()
    eName =  row.pName.encode('gbk')
    mobile = row.pMobile.encode('gbk')
    address = "%s-%s"%(row.communityName.encode('gbk'),ad)
    sql_insert = """insert into zhsq_express(trackid, expresstype, fromuser, touser, address,phone, createtime, status,userid,detailaddress) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s','%s')""" % (
        "", msg, "", eName, address, mobile,
        datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), '1', eid,"")
    print type(sql_insert),sql_insert
    se.execute(sql_insert.decode('gbk'))
    mailsql = "insert into zhsq_jpush ( status, titleid,title, userid, createtime, content, pushtype,usertype) values (  '1', '2', '快递', '%s', '%s', '您有新快递' , '0','1')" % (mobile.decode('gbk').encode('utf-8'),datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    se.execute(mailsql.decode('utf-8'))
    print mailsql
    return HttpResponseRedirect( '/CMS/express/addexpress.ht?search=%s&strExpressType=%s'%(search.decode('gbk').encode('utf-8'),msg.decode('gbk').encode('utf-8')))

#增加快递接口
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def saveexpress_old(req):
    se = settings.DB_SESSION()
    try:
        # 获取请求对象
        flag, reqobj = get_reqobj(req)
        if not flag:
            return HttpResponse(
                sjapi.jsondumps({'rspcode': 8004, 'rspinfo': reqobj}, ensure_ascii=False, encoding='utf-8'),
                content_type='application/json; charset=utf-8')
        # 获取请求要素
        # 快递编号
        trackid = reqobj.get('strTrackId', '')
        # 快递类型 如中通快递、百世快递
        expresstype = reqobj.get('strExpressType', '')
        # 发件人
        fromuser = reqobj.get('strFromUser', '')
        #收件人
        touser = reqobj.get('strToUser', '')
        #收件人地址
        #小区id
        cid = reqobj.get('strCommunityId')
        #楼栋号
        belongBuildingNum = reqobj.get('belongBuildingNum', '')
        #单元号
        belongBuildingUnit = reqobj.get('belongBuildingUnit', '')
        #门牌号
        houseNum = reqobj.get('houseNum', '')
        address = cid +'-'+ belongBuildingNum + '-' + belongBuildingUnit + '-' + houseNum
        try:
            hid_sql = """select hid from zhsq_house where communityId ='%s' and belongBuildingNum = '%s' and belongBuildingUnit ='%s' and houseNum = '%s'"""%(cid, belongBuildingNum,belongBuildingUnit,houseNum)
            hid = se.execute(hid_sql.decode('utf-8')).fetchone().hid
            user_sql = """select * from zhsq_house2owner where hid ='%s' """ % hid
            pid = se.execute(user_sql.decode('utf-8')).fetchone()
            comName = pid.communityName if pid.communityName else ''
            detailaddress = comName +'小区'+belongBuildingNum+'号楼'+belongBuildingUnit +'单元'+houseNum
        except:
            return HttpResponse(
                sjapi.jsondumps({'rspcode': 8999, 'rspinfo': '暂无此数据信息'}, ensure_ascii=False, encoding='utf-8'),
                content_type='application/json; charset=utf-8')
        #收件人电话
        phone = reqobj.get('strPhone', '')
        try:
            sql_insert = """insert into zhsq_express(trackid, expresstype, fromuser, touser, address,phone, createtime, status,userid,detailaddress) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s','%s')""" % (
            trackid, expresstype, fromuser, touser, address,phone, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), '1',pid.pid,detailaddress)
            print sql_insert
        except :
            sql_insert = """insert into zhsq_express(trackid, expresstype, fromuser, touser, address,phone, createtime, status,userid,detailaddress) values ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s','%s','%s')""" % (
                trackid, expresstype, fromuser, touser, address, phone,
                datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), '1', pid,detailaddress)
        se.execute(sql_insert.decode('utf-8'))
        # 放在消息表中 1未下发 1已接单0推送 2快递
        try:
            mailsql = "insert into zhsq_jpush ( status, titleid,title, userid, createtime, content, pushtype,usertype) values (  '1', '2', '快递', '%s', '%s', '您有新快递' , '0','3')" % (
            pid.pMobile, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        except:
            mailsql = "insert into zhsq_jpush ( status, titleid,title, userid, createtime, content, pushtype,usertype) values (  '1', '2', '快递', '', '%s', '您有新快递' , '0','3')" % (
               datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
        se.execute(mailsql.decode('utf-8'))

        se.close()
        return HttpResponse(
            sjapi.jsondumps({'rspcode': 0, 'rspinfo': 'ok'}, ensure_ascii=False, encoding='utf-8'),
            content_type='application/json; charset=utf-8')
    except Exception as e:
        se.close()
        return HttpResponse(
            sjapi.jsondumps({'rspcode': 8999, 'rspinfo': '数据请求失败'}, ensure_ascii=False, encoding='utf-8'),
            content_type='application/json; charset=utf-8')

def delexpress(req):
    se = settings.DB_SESSION()
    try:
        # 删除批评表扬的id
        flag, reqobj = get_reqobj(req)
        if not flag: return HttpResponse({'rspcode': 8004, 'rspinfo': reqobj})
        id = reqobj.get('id')
        update_sql = """update zhsq_express set status ='3'where id='%s'""" % (id)
        se.execute(update_sql.decode('utf-8'))
        se.close()
        content = {"code":0,"message":None,"exception":None}
        return HttpResponse(
            sjapi.jsondumps(content, ensure_ascii=False, encoding='utf-8'),
            content_type='application/json; charset=utf-8')
    except Exception as e:
        se.close()
        return HttpResponse(
            sjapi.jsondumps({"code":0,"message":None,"exception":None}, ensure_ascii=False, encoding='utf-8'),
            content_type='application/json; charset=utf-8')

def delall( req ):
    flag, reqobj = get_reqobj( req )
    if not flag: return HttpResponse( {  'rspcode': 8004, 'rspinfo': reqobj } )
    ids = reqobj.getlist('ids')
    se = settings.DB_SESSION()
    for id in ids:
        #sql =  "delete from zhsq_information where messageNo = '%s'" %(id)
        sql = """update zhsq_express set status ='3'where id='%s'""" % (id)
        log.info("owner",sql)
        se.execute( sql.decode('gbk') )
    content = {}
    content = {"message":"操作成功","messageCode":0}
    content = {"code":0,"message":None,"exception":None}
    return HttpResponse( sjapi.jsondumps( content , ensure_ascii = False , encoding = 'utf-8' ), content_type='application/json; charset=gbk' )


def delexpress_old(req):
    se = settings.DB_SESSION()
    try:
        # 删除批评表扬的id
        flag, reqobj = get_reqobj(req)
        if not flag: return HttpResponse({'rspcode': 8004, 'rspinfo': reqobj})
        ids = reqobj.get('strId')
        for id in ids:
            update_sql = """update zhsq_express set status ='3'where id='%s'""" % (id)
            se.execute(update_sql.decode('utf-8'))
        se.close()
        return HttpResponse(
            sjapi.jsondumps({'rspcode': 0, 'rspinfo': 'ok'}, ensure_ascii=False, encoding='utf-8'),
            content_type='application/json; charset=utf-8')
    except Exception as e:
        se.close()
        return HttpResponse(
            sjapi.jsondumps({'rspcode': 8004, 'rspinfo': '服务器请求异常'}, ensure_ascii=False, encoding='utf-8'),
            content_type='application/json; charset=utf-8')


def selcommunity(req):
    se = settings.DB_SESSION()
    communityid = req.session['communityid']
    sql = "select * from zhsq_community where companyId ='%s'"%communityid
    log.info('communityid', sql)
    rs = se.execute(sql).fetchall()
    row = []
    content = {}
    for result in rs:
        content = {'strcommunityId': str(result.communityVettedId), 'strComname': result.comName}
        row.append(content)
        content = {}
    se.close()
    return HttpResponse(sjapi.jsondumps(row, ensure_ascii=False, encoding='utf-8'),
                        content_type='application/json; charset=utf-8')


def downpage(req):
    return render_to_response('CMS/downpage/property.html')
